package com.zxh.blog.web.security.controller;

import com.zxh.blog.redis.FastJsonRedisSerializer;
import com.zxh.blog.redis.service.RedisService;
import com.zxh.blog.utils.JwtTokenUtil;
import com.zxh.blog.utils.SecurityContextHolder;
import com.zxh.blog.vo.RedisVo;
import com.zxh.blog.web.security.entity.SysUser;
import com.zxh.blog.web.security.service.SysUserService;
import com.zxh.blog.web.security.vo.AuthenticationToken;
import com.zxh.blog.web.security.vo.AuthorizationUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;

import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * @author zxh
 * @Title: LoginController
 * @ProjectName blog-system
 * @Description: TODO
 * @date 2019/2/1614:49
 */
@RestController()
@RequestMapping(value = "/auth")
public class LoginController {
    @Value("Authorization")
    private String tokenHeader;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    @Qualifier("sysUserService")
    private SysUserService sysUserService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private SecurityContextHolder securityContextHolder;

    /**
     * 登录授权
     * @param authorizationUser
     * @return
     */
    @PostMapping(value = "/login")
    public ResponseEntity login(@RequestBody  AuthorizationUser authorizationUser){

        final SysUser userDetails = (SysUser)sysUserService.loadUserByUsername(authorizationUser.getUsername());
        if(userDetails==null || userDetails.getPassword()==""){
            throw new AccountExpiredException("账号或者密码错误");
        }
        if(!userDetails.getPassword().equals(authorizationUser.getPassword())){
            throw new AccountExpiredException("账号或者密码错误");
        }

        if(!userDetails.isEnabled()){
            throw new AccountExpiredException("账号已停用，请联系管理员");
        }

        // 生成令牌
        final String token = jwtTokenUtil.generateToken(userDetails);
        FastJsonRedisSerializer<SysUser> sysUserFastJsonRedisSerializer=new FastJsonRedisSerializer<SysUser>(SysUser.class);
        RedisVo redisVo=new RedisVo(token,SysUser.class.getName(),sysUserFastJsonRedisSerializer.serialize(userDetails));
        redisService.saveByteValue(redisVo);
        // 返回 token
        return ResponseEntity.ok(new AuthenticationToken(token));
    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping(value = "/info")
    public ResponseEntity getUserInfo(HttpServletRequest request){
        UserDetails userDetails = securityContextHolder.getUserDetails(request);
        SysUser jwtUser = (SysUser)sysUserService.loadUserByUsername(userDetails.getUsername());
        return ResponseEntity.ok(jwtUser);
    }
    /**
     * 获取用户信息
     * @return
     */
    @GetMapping(value = "/findbyUserName")
    public ResponseEntity findbyUserName(String username){
        SysUser jwtUser=new SysUser();
        jwtUser.setUsername(username);
        List<SysUser> list= sysUserService.queryAll(jwtUser);
        String msg=list.size()>0?"该用户已存在！":"ok";
        return ResponseEntity.ok(msg);
    }

    @PostMapping(value = "/register")
    public ResponseEntity register(@RequestBody  SysUser sysUser){
        sysUser.setUserId(UUID.randomUUID().toString());
        sysUser.setStatus(1);
        sysUser.setCreateTime(new Date());
        String msg=sysUserService.register(sysUser);
        return ResponseEntity.ok(msg);
    }


}
